package ro.msg.quiz.repository;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.util.ArrayList;

import ro.msg.quiz.Model.*;
import ro.msg.quiz.controller.Controller;
import ro.msg.quiz.controller.QuizController;
/**
 *
 * @author Alexandra
 * This class imports objects from xml file
 */

public class JaxbXMLToJava {


	public static final String xmlFileQuestion = "ImportQuestion.xml";
	public static final String xmlFileQuiz = "ImportQuiz.xml";
	public static final String xmlFileRelation = "ImportRelation.xml";

    private int idQuestion, idQuiz, type, correctAnswer;
    private String text, answer;
    private ArrayList<String> answers = new ArrayList<String>();
    private ArrayList<Integer> correctAnswers = new ArrayList<Integer>();
    private Question question = new Question();
    private Quiz quiz = new Quiz();
    private  String quizName;
    
    ArrayList<Question> questionsList;
	ArrayList<Quiz> quizList;
	RepositoryQuestion repQuestion; 
	RepositoryQuiz repQuiz;
	final IQuizModel model; 
	final Controller controller;
    
    /**
     * Constructor
     * @throws IOException 
     * @throws SAXException 
     * @throws ParserConfigurationException 
     */
    public JaxbXMLToJava() {
    	questionsList = new ArrayList<Question>();
    	quizList = new ArrayList<Quiz>();
    	repQuestion = new RepositoryQuestion(questionsList);
    	repQuiz = new RepositoryQuiz(quizList);
    	model = new QuizModel(repQuestion, repQuiz);
    	controller = new Controller(model);
    }

	/**
	 * This method import questions from xml file
	 */
    public void importQuestionFromXML(String path) throws ParserConfigurationException, SAXException, IOException {

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder db = dbf.newDocumentBuilder();
		Document doc = db.parse(path + xmlFileQuestion);
		doc.getDocumentElement().normalize();

		System.out.println("Root element : " + doc.getDocumentElement().getNodeName());
		NodeList nListQ = doc.getElementsByTagName("question");
       	System.out.println("------------------------------------------------------------------");
       	int nListQSize = nListQ.getLength();
       	for (int temp = 0; temp < nListQSize; temp++) {

            Node nNode = nListQ.item(temp);
            System.out.println("Question " + temp );

            if (nNode.getNodeType() == Node.ELEMENT_NODE ) {

            	Element eElement = (Element) nNode;

                idQuestion = Integer.parseInt(eElement.getElementsByTagName("id").item(0).getTextContent());
                type = Integer.parseInt(eElement.getElementsByTagName("type").item(0).getTextContent());
                text = eElement.getElementsByTagName("text").item(0).getTextContent();

                //Print to console
                System.out.println("id " + eElement.getElementsByTagName("id").item(0).getTextContent());
                System.out.println("type " + eElement.getElementsByTagName("type").item(0).getTextContent());
                System.out.println("text " + eElement.getElementsByTagName("text").item(0).getTextContent());

                // for singleChoiceQ
                if( type == 1 ) {

                    for(int i = 0; i < eElement.getElementsByTagName("option").getLength(); i++ ) {

                        answer = eElement.getElementsByTagName("option").item(i).getTextContent();
                        answers.add(answer);
                        System.out.println("Answer " + i + ":  "+
                        					eElement.getElementsByTagName("option").item(i).getTextContent());
                        answers.clear();
                    }

                    correctAnswer = Integer.parseInt(eElement.getElementsByTagName("correctOption").item(0).getTextContent());
                    System.out.println("Correct answer: "  +
                    						eElement.getElementsByTagName("correctOption").item(0).getTextContent());
                    question = new SingleChoiceQ( idQuestion, text, answers, correctAnswer );
                    System.out.println();
                }
                else
                {
                    // for multipleChoiceQ
                    if( type == 2) {

                    	int noOfOptions = Integer.parseInt(eElement.getElementsByTagName("noOfOptions").item(0).getTextContent());

                    	for(int i = 0; i < eElement.getElementsByTagName("option").getLength(); i++ ) {

                             answer = eElement.getElementsByTagName("option").item(i).getTextContent();
                             answers.add(i, answer);
                             System.out.println("Answer " + i + ":  " +
                            		 	Integer.parseInt(eElement.getElementsByTagName("option").item(i).getTextContent()));
                        }

                        for( int i = 0; i < eElement.getElementsByTagName("correctAnswer").getLength(); i++ ) {

                        	correctAnswer = Integer.parseInt(eElement.getElementsByTagName("correctAnswer").item(i).getTextContent());
                            correctAnswers.add(i, correctAnswer);
                            System.out.println("Correct answer "  + i + ":  " +
                            			eElement.getElementsByTagName("correctAnswer").item(i).getTextContent() );
                        }
                        question = new MultipleChoiceQ( idQuestion, text, noOfOptions, answers, correctAnswers );
                        System.out.println();
                        answers.clear();
                    }
                   else
                    {
                        // for textQ
                	   if( type == 3 ) {

                		   answer = eElement.getElementsByTagName("answer").item(0).getTextContent();
                           System.out.println("Correct answer: "  +
                        		   			eElement.getElementsByTagName("answer").item(0).getTextContent());
                           question = new TextQ( idQuestion, text, answer );
                           System.out.println();
                	   }

                    }
                }
            }

            repQuestion.addQuestion(question);
        }
    }

    /**
	 * This method import quizzes from xml file
	 */
    public void importQuizFromXML(String path) throws ParserConfigurationException, SAXException, IOException {


        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(path + xmlFileQuiz);
        doc.getDocumentElement().normalize();

        System.out.println("Root element : " + doc.getDocumentElement().getNodeName());
        NodeList nListQ = doc.getElementsByTagName("quiz");

        System.out.println("------------------------------------------------------------------");
        int nListQSize = nListQ.getLength();
        for (int temp = 0; temp < nListQSize; temp++) {

            Node nNode = nListQ.item(temp);
            System.out.println("Quiz " + temp );

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            	Element eElement = (Element) nNode;
                idQuiz = Integer.parseInt(eElement.getElementsByTagName("id").item(0).getTextContent());
                quizName = eElement.getElementsByTagName("quizName").item(0).getTextContent();
                quiz.setId(idQuiz);
                quiz.setQuizName(quizName);
                //Print to console
                System.out.println("id " + eElement.getElementsByTagName("id").item(0).getTextContent());
                System.out.println("quizName " + eElement.getElementsByTagName("quizName").item(0).getTextContent());
            }
            repQuiz.addQuiz(quiz);
        }
    }


    /**
     * THis method imports the relations between quizzes and questions
     * @throws ParserConfigurationException
     * @throws IOException
     * @throws SAXException
     */
    public void importRelationQuizQuestion(String path) throws ParserConfigurationException, SAXException, IOException {

    	DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document doc = db.parse(xmlFileRelation);
        doc.getDocumentElement().normalize();
        
        importQuestionFromXML(path);
        importQuizFromXML(path);
        model.setQuestionRepo(this.repQuestion);
        model.setQuizRepo(this.repQuiz);
        System.out.println("Root element : " + doc.getDocumentElement().getNodeName());
        NodeList nListQ = doc.getElementsByTagName("relation");

        System.out.println("------------------------------------------------------------------");
        int nListQSize = nListQ.getLength();
        for (int temp = 0; temp < nListQSize; temp++) {

            Node nNode = nListQ.item(temp);
            System.out.println("Relation " + temp );

            if (nNode.getNodeType() == Node.ELEMENT_NODE) {

            	Element eElement = (Element) nNode;
                idQuiz = Integer.parseInt(eElement.getElementsByTagName("idQuiz").item(0).getTextContent());
                idQuestion = Integer.parseInt(eElement.getElementsByTagName("idQuestion").item(0).getTextContent());
                model.addQuestionToQuiz(idQuiz, idQuestion);

                //Print to console
                System.out.println("idQuiz " + eElement.getElementsByTagName("idQuiz").item(0).getTextContent());
                System.out.println("idQuestion: " + eElement.getElementsByTagName("idQuestion").item(0).getTextContent());
            }
        }
    }
}



